from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
from datetime import datetime, timedelta

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# 模拟的用户数据，包括班级信息
users = {
    'teacher': [],
    'student': [],
    'parent': []
}

# 模拟的班级数据
classes = {}

# 模拟考试数据
exams = {}
cheating_records = {}  # 记录作弊次数

# 登录
@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        password = request.form['password']

        if user_type in users:
            for user in users[user_type]:
                if user['username'] == username and user['password'] == password:
                    session['username'] = username
                    session['user_type'] = user_type
                    if user_type == 'student':
                        return redirect(url_for('student_dashboard', username=username))
                    elif user_type == 'teacher':
                        return redirect(url_for('teacher_dashboard', username=username))
                    elif user_type == 'parent':
                        return redirect(url_for('parent_dashboard', username=username))
        flash('登录失败，用户名或密码错误！', 'danger')
        return redirect(url_for('login'))

    return render_template('login.html')

# 注册
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        machine_id = request.form['machine_id']
        password = request.form['password']

        # 检查用户名是否已存在
        for user_type_key in users:
            for user in users[user_type_key]:
                if user['username'] == username:
                    flash('用户名已存在，请选择其他用户名。', 'danger')
                    return redirect(url_for('register'))

        # 添加新用户，包含用户的用户名、机号和密码
        users[user_type].append({'username': username, 'machine_id': machine_id, 'password': password, 'class': None})
        flash('注册成功！', 'success')
        return redirect(url_for('register_success'))

    return render_template('register.html')

@app.route('/register_success')
def register_success():
    return render_template('register_success.html')

# 忘记密码
@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        new_password = request.form['new_password']

        # 查找并更新用户密码
        user_found = False
        if user_type in users:
            for user in users[user_type]:
                if user['username'] == username:
                    user['password'] = new_password
                    user_found = True
                    flash('密码重置成功！', 'success')
                    return redirect(url_for('password_reset_success'))

        if not user_found:
            flash('用户名不存在。', 'danger')
            return redirect(url_for('forgot_password'))

    return render_template('forgot_password.html')

@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')

# 学生页面
@app.route('/student_dashboard/<username>', methods=['GET', 'POST'])
def student_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    if request.method == 'POST':
        class_name = request.form['class_name']
        for student in users['student']:
            if student['username'] == username:
                student['class'] = class_name
                if class_name not in classes:
                    classes[class_name] = []
                classes[class_name].append(username)
                flash(f'成功加入班级 {class_name}！', 'success')
                return redirect(url_for('student_class', username=username, class_name=class_name))

    student_class_name = next((student['class'] for student in users['student'] if student['username'] == username),
                              None)
    return render_template('student_dashboard.html', username=username, class_name=student_class_name)

# 学生选择加入考试页面
@app.route('/student_class/<username>/<class_name>', methods=['GET', 'POST'])
def student_class(username, class_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    if request.method == 'POST':
        exam_name = request.form.get('exam_name')
        if exam_name in exams and exams[exam_name]['class_name'] == class_name:
            if username in exams[exam_name].get('participants', []):
                flash('你已经参加过此考试，不能再次加入。', 'danger')
                return redirect(url_for('student_class', username=username, class_name=class_name))

            if 'participants' not in exams[exam_name]:
                exams[exam_name]['participants'] = []
            exams[exam_name]['participants'].append(username)

            session['exam'] = exams[exam_name]
            session['exam_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
            return redirect(url_for('exam_page', class_name=class_name, exam_name=exam_name))

        flash('没有找到该考试。', 'danger')
        return redirect(url_for('student_class', username=username, class_name=class_name))

    exam_list = [exam_name for exam_name, exam_info in exams.items()
                 if exam_info['class_name'] == class_name and username not in exam_info.get('participants', [])]
    return render_template('student_class.html', username=username, class_name=class_name, exams=exam_list)

# 考试页面
@app.route('/exam/<class_name>/<exam_name>', methods=['GET', 'POST'])
def exam_page(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    exam = exams.get(exam_name)
    if exam:
        remaining_time = exam['end_time'] - datetime.now()
        if remaining_time.total_seconds() <= 0:
            flash('考试时间已到，系统已自动提交。', 'warning')
            return redirect(url_for('exam_finished', class_name=class_name, exam_name=exam_name))

        remaining_seconds = int(remaining_time.total_seconds())

        return render_template('exam.html', remaining_time=remaining_seconds, class_name=class_name,
                               exam_name=exam_name)

    flash('没有找到考试信息。', 'danger')
    return redirect(url_for('student_class', username=session.get('username'), class_name=class_name))

# 新增的考试完成页面
@app.route('/exam_finished/<class_name>/<exam_name>', methods=['GET'])
def exam_finished(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name,
                           username=session['username'])

@app.route('/submit_exam/<class_name>/<exam_name>', methods=['POST'])
def submit_exam(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    exam = exams.get(exam_name)
    if exam:
        try:
            exam_start_time_str = session.get('exam_start_time')
            if not exam_start_time_str:
                raise ValueError("考试开始时间未找到")

            exam_start_time = datetime.strptime(exam_start_time_str, '%Y-%m-%d %H:%M:%S.%f')
            elapsed_time = datetime.now() - exam_start_time
            elapsed_seconds = int(elapsed_time.total_seconds())

            session.pop('exam', None)
            session.pop('exam_start_time', None)

            return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name,
                                   elapsed_seconds=elapsed_seconds, username=session['username'])
        except Exception as e:
            return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name, error=str(e),
                                   username=session['username'])

    flash('考试提交失败，未找到考试信息。', 'danger')
    return redirect(url_for('student_class', username=session.get('username'), class_name=class_name))

# 老师页面
@app.route('/teacher_dashboard/<username>', methods=['GET', 'POST'])
def teacher_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        if 'add_exam' in request.form:
            return redirect(url_for('set_exam_time', username=username))

    return render_template('teacher_dashboard.html', username=username)

@app.route('/manage_class/<username>', methods=['GET', 'POST'])
def manage_class(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        class_name = request.form.get('class_name', '')
        if not class_name:
            flash('班级名称不能为空', 'danger')
            return redirect(url_for('manage_class', username=username))

        return redirect(url_for('class_management', class_name=class_name))

    return render_template('teacher_dashboard.html', username=username)

@app.route('/class_management/<class_name>', methods=['GET'])
def class_management(class_name):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    students = classes.get(class_name, [])
    ongoing_exams = [exam_name for exam_name, exam_info in exams.items() if
                     exam_info['class_name'] == class_name and datetime.now() < exam_info['end_time']]

    return render_template('class_management.html', class_name=class_name, students=students,
                           ongoing_exams=ongoing_exams)

# 设置考试时间页面
@app.route('/set_exam_time/<username>', methods=['GET', 'POST'])
def set_exam_time(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        exam_name = request.form.get('exam_name', '')
        class_name = request.form.get('class_name', '')
        exam_duration = request.form.get('exam_duration', '')
        if not exam_name or not class_name or not exam_duration:
            flash('考试名称、班级名称和考试时长不能为空', 'danger')
            return redirect(url_for('set_exam_time', username=username))

        end_time = datetime.now() + timedelta(minutes=int(exam_duration))
        exams[exam_name] = {
            'class_name': class_name,
            'start_time': datetime.now(),
            'end_time': end_time,
            'participants': []
        }
        flash(f'考试 {exam_name} 设置成功！', 'success')
        return redirect(url_for('class_management', class_name=class_name))

    class_list = list(classes.keys())

    return render_template('set_exam_time.html', username=username, classes=class_list)

# 家长页面
@app.route('/parent_dashboard/<username>')
def parent_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'parent':
        return redirect(url_for('login'))

    return render_template('parent_dashboard.html', username=username)

# 记录作弊行为
@app.route('/record_cheating', methods=['POST'])
def record_cheating():
    if 'username' in session:
        username = session['username']
        if username not in cheating_records:
            cheating_records[username] = 0
        cheating_records[username] += 1

        max_cheat_attempts = 2
        if cheating_records[username] > max_cheat_attempts:
            return jsonify({'terminate': True})
        return jsonify({'terminate': False})
    return jsonify({'error': 'User not logged in'}), 401

# 终止考试
@app.route('/terminate_exam')
def terminate_exam():
    session.pop('exam', None)
    flash("由于检测到多次作弊行为，您的考试已被终止。", 'danger')
    return redirect(url_for('login'))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
